import React, {Component, createRef} from 'react';
import classnames from 'classnames'

class Main extends Component {


  list = {}

  state = {
    currentName: '',
    currentId: ''
  }
  onChange = (id) => e => {
    // console.log(e.target.checked)
    this.props.onChange(id, e.target.checked)
  }

  changeAll = (e) => {
    console.log(e.target.checked)
    this.props.changeAll(e.target.checked)
  }

  edit = (item) => () => {
    this.setState({
      currentName: item.title,
      currentId: item.id
    }, () => {
      this.list[item.id].focus()
      this.list[item.id].select()
    })
  }

  onKeyDown = (e) => {
    console.log('324')
    if (e.keyCode === 13) {
      console.log('234234')
      this.props.editTodo(this.state.currentName, this.state.currentId)
      this.onBlur()
    }
  }

  onBlur = () => {
    this.setState({
      currentId: '',
      currentName: ''
    })
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // this.inputRef.current.focus()
  }


  render() {
    const {list} = this.props


    return (
      <section className="main">
        <input id="toggle-all" className="toggle-all" type="checkbox" value={this.props.checkAll}
               onChange={this.changeAll}/>
        <label htmlFor="toggle-all">Mark all as complete</label>
        <ul className="todo-list">
          {
            list.map(item => (
              <li
                key={item.id}
                className={classnames({completed: item.isDone, editing: this.state.currentId === item.id})}
              >
                <div className="view">
                  <input
                    className="toggle"
                    onChange={this.onChange(item.id)}
                    type="checkbox"
                    checked={item.isDone}
                  />
                  <label onDoubleClick={this.edit(item)}>{item.title}</label>
                  <button
                    className="destroy"
                    onClick={this.props.delTodo(item.id)}
                  />
                </div>
                {
                  <input
                    onBlur={this.onBlur}
                    ref={ref => this.list[item.id] = ref}
                    value={this.state.currentName}
                    className="edit"
                    onChange={(e) => this.setState({currentName: e.target.value})}
                    onKeyDown={this.onKeyDown}
                  />
                }
              </li>
            ))
          }
        </ul>
      </section>
    );
  }
}

export default Main;
